$(function() {

	var consolePanel = $('.panel-body'),
		consoleDiv = $('pre'),
		errorModal = $('.modal');

	consolePanel.height($(window).height() - 190);
	$(window).resize(function() {
		consolePanel.height(Math.max($(this).height() - 190, 300));
	});

	var DOMAIN_PATH = '/apps-deploy',
		APP_DEPLOY_BY_BAME_URL = DOMAIN_PATH + '/apps/action/deploy/name/',
		APP_RECORD_BY_NAME_URL = DOMAIN_PATH + '/apps/record/name/';

	$('button').on('click', function() {
		var appName = $(this).siblings('.active').text();
		$.get(APP_DEPLOY_BY_BAME_URL + appName, function(result) {
			if (result.succeeded) {
				getRecordByName(appName);
			} else {
				errorModal.find('.modal-body').text(result.message);
				errorModal.modal('show');
			}
		});
	});

	function getRecordByName(name) {
		$.get(APP_RECORD_BY_NAME_URL + name, function(result) {
			if (result.succeeded) {
				consoleDiv.append(result.message);
				if (!result.finished) {
					getRecordByName(name);
				} else {
					consoleDiv.append('<<<< End >>>>');
				}
			} else {
				errorModal.find('.modal-body').text(result.message);
				errorModal.modal('show');
			}
		});
	}

	errorModal.on('hide.bs.modal', function() {
		$(this).find('.modal-body').text('');
	});
});